<template>
  <div class="app-container">
    <template v-if="isLoggedIn">
      <!-- 左侧侧边栏 -->
      <Sidebar @nav-click="handleNavClick" :user-info="userInfo" :unread-friend-requests="unreadFriendRequests"
        @create-group="enterGroupCreateMode" @add-friend="enterAddFriendMode" @logout="logout" />
      <!-- 中间内容区 -->
      <div class="main-content">
        <!-- 会话列表 -->
        <ChatSidebar ref="chatSidebarRef" :external-contacts="addedContacts" @contact-selected="onContactSelected"
          @create-group-click="enterGroupCreateMode" @go-to-chat="onContactSelected"
          @send-friend-request="sendFriendRequest" v-if="currentView === 'chats' || currentView === 'chat'" />
        <!-- 好友列表 -->
        <FriendList ref="friendListRef" :userId="userInfo.id" :unread-requests="unreadFriendRequests"
          @select-friend="onFriendSelected" @load-messages="onLoadMessages" @create-group="createGroupChat"
          @enter-new-friends="enterAddFriendMode" :is-group-mode="isGroupCreateMode"
          v-if="currentView === 'contacts'" />
        <!-- 聊天窗口 -->
        <ChatWindow ref="chatWindowRef" :contact="selectedContact" @message-sent="syncNewMessageToChatSidebar"
          v-if="currentView === 'chat'" />
        <!-- 添加好友界面（仅显示好友请求） -->
        <AddFriend ref="addFriendRef" v-if="currentView === 'add-friend'" :userId="userInfo.id"
          @close="currentView = 'contacts'" @refresh-friends="refreshFriendList"
          @request-processed="loadUnreadFriendRequests" />
      </div>
    </template>
    <AuthView v-else @login-success="handleLoginSuccess" />
  </div>
</template>

<script setup>
import { ref, shallowRef, onMounted, onUnmounted, watch } from 'vue';
import { parseToken } from './utils/jwt';
import Sidebar from './components/Sidebar.vue';
import ChatSidebar from './components/ChatSidebar.vue';
import FriendList from './components/FriendList.vue';
import ChatWindow from './components/ChatWindow.vue';
import AddFriend from './components/AddFriend.vue';
import AuthView from './views/AuthView.vue';
import request from './utils/request';

createAiChat({
  appId: "1937711745741131778",
  // 支持top-left左上, top-right右上, bottom-left左下, bottom-right右下
  iconPosition: "top-right"
});
// 状态管理
const isLoggedIn = ref(!!localStorage.getItem('token'));
const userInfo = ref({ userName: '', avatarUrl: '', id: '' });
const currentView = ref('chats'); // 视图状态：chats/contacts/chat/add-friend
const selectedContact = ref(null);
const addedContacts = ref([]);
const friendList = ref([]); // 用于群聊创建的好友列表缓存
const unreadFriendRequests = ref(0); // 未读好友请求数量

// 组件引用
const chatSidebarRef = shallowRef(null);
const chatWindowRef = shallowRef(null);
const friendListRef = shallowRef(null);
const addFriendRef = shallowRef(null);

// 群聊创建相关状态
const isGroupCreateMode = ref(false);
const selectedGroupMembers = ref([]);

// WebSocket相关
const ws = ref(null);
const wsConnected = ref(false);
let reconnectTimer = null;
const pendingMessages = ref([]);
const mountTime = ref(null);

onMounted(() => {
  mountTime.value = new Date();
  if (isLoggedIn.value) {
    initUserInfo();
    initWebSocket();
    loadFriendListForGroup();
    loadUnreadFriendRequests(); // 初始化未读请求数量
  }
});

onUnmounted(() => {
  disconnectWebSocket();
});

// 监听视图切换，处理未读消息
watch(currentView, (newView) => {
  if (newView === 'chats') processPendingMessages();
  // 进入添加好友页面时清零未读数量（已读状态）
  if (newView === 'add-friend') {
    unreadFriendRequests.value = 0;
  }
});

// 初始化用户信息
const initUserInfo = () => {
  try {
    const token = localStorage.getItem('token');
    const userInfoStorage = JSON.parse(localStorage.getItem('user_info') || '{}');
    const parsed = parseToken(token);

    userInfo.value = {
      userName: parsed.userName || userInfoStorage.userName || '用户',
      avatarUrl: parsed.avatarUrl || userInfoStorage.avatarUrl || '/images/avatar-default.png',
      id: parsed.id || userInfoStorage.id || ''
    };
  } catch (error) {
    console.error('解析用户信息失败', error);
    logout();
  }
};

// 确保未读数量仅统计pending状态的请求
const loadUnreadFriendRequests = async () => {
  try {
    const userId = localStorage.getItem('userId');
    if (!userId) return;

    const res = await request.get('/user/getRequestMessage', {
      params: { userId }
    });

    if (['SUCCESS', 'SUCCESs'].includes(res.data.code)) {
      // 只统计未处理的请求
      const pendingRequests = res.data.data.filter(req => req.status === 'pending');
      unreadFriendRequests.value = pendingRequests.length;
    }
  } catch (error) {
    console.error('加载未读请求失败', error);
  }
};

// WebSocket初始化(这里就已经连接好了websocket)
const initWebSocket = () => {

  if (!isLoggedIn.value) return;

  try {
    const token = localStorage.getItem('token');
    if (!token) throw new Error('无登录令牌');

    disconnectWebSocket();
    const wsUrl = `ws://127.0.0.1:8083/message?token=${token}`;//这里就是连接的
    ws.value = new WebSocket(wsUrl);

    //刚连接成功，就立即调用
    ws.value.onopen = () => {
      console.log('WebSocket连接成功');
      wsConnected.value = true;
      clearReconnectTimer();
      processPendingMessages();
      // 连接成功后检查离线好友请求
      if (currentView.value !== 'add-friend') checkOfflineFriendRequests();
    };
    //实时接受信息
    ws.value.onmessage = async (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.type === 'message') {
          await processIncomingMessage(data);
        } else if (data.type === 'friend_request') {
          // 处理好友请求消息（实时通知）
          await processFriendRequest(data);
        }
      } catch (error) {
        console.error('WebSocket消息处理失败:', error);
      }
    };
    const handleLogout = () => {
      logout();
    };
    ws.value.onclose = () => {
      console.log('WebSocket断开连接');
      wsConnected.value = false;
      scheduleReconnect();
    };

    ws.value.onerror = (error) => {
      console.error('WebSocket错误:', error);
      wsConnected.value = false;
      scheduleReconnect();
    };
  } catch (error) {
    console.error('WebSocket初始化失败:', error);
    // 未登录状态下不进行重连
    if (isLoggedIn.value) {
      scheduleReconnect();
    }
  }
};

// 处理好友请求（实时更新未读数量）
const processFriendRequest = async (data) => {
  console.log('收到好友请求:', data);

  // 1. 无论当前在哪个页面，先刷新未读数量
  await loadUnreadFriendRequests();

  // 2. 如果在添加好友页面，同时刷新请求列表
  if (currentView.value === 'add-friend' && addFriendRef.value) {
    addFriendRef.value.loadFriendRequests();
  } else if (chatSidebarRef.value) {
    // 在聊天页面时也刷新好友请求列表
    chatSidebarRef.value.loadFriendRequests();
  }
};

const checkOfflineFriendRequests = async () => {
  try {
    const userId = localStorage.getItem('userId');
    const res = await request.get('/user/getRequestMessage', { params: { userId } });

    if (['SUCCESS', 'SUCCESs'].includes(res.data.code) && res.data.data.length > 0) {
      const pendingRequests = res.data.data.filter(req => req.status === 'pending');
      if (pendingRequests.length > 0) {
        // 仅更新未读数量，不弹窗
        unreadFriendRequests.value = pendingRequests.length;
      }
    }
  } catch (error) {
    console.error('检查离线好友请求失败:', error);
  }
};

// 消息处理（你看这里有消息处理，但是没有好友请求处理）
const processIncomingMessage = async (data) => {
  // 给 isGroup 设置默认值，这里假设默认是 false，可根据实际需求调整
  const { dialogueId, content, fromId, fromName, isGroup = false } = data;
  const isSelf = fromId === userInfo.value.id;
  const avatarUrl = isSelf ? userInfo.value.avatarUrl : '/images/avatar-default.png';

  const newMsg = {
    sender: isSelf ? '我' : fromName || '对方用户',
    content,
    time: new Date().toISOString(),
    isSelf,
    avatarUrl,
    isAfterMount: new Date() >= mountTime.value,
    isRead: false
  };


  // 更新会话列表
  if (chatSidebarRef.value && ['chats', 'chat'].includes(currentView.value)) {
    chatSidebarRef.value.updateWithNewMessage(dialogueId, newMsg);
  } else {
    pendingMessages.value.push({ dialogueId, message: newMsg });
  }
  // 群聊消息需要特殊处理，确保即使不是当前选中的联系人也能更新
  const isGroupChat = selectedContact.value?.isGroup || false;
  const shouldUpdateChat = currentView.value === 'chat' &&
    (selectedContact.value?.dialogueId === dialogueId ||
      (isGroupChat && isGroup));
  if (shouldUpdateChat) {
    console.log('收到群聊消息：', newMsg)
    // selectedContact.value.messages = [...(selectedContact.value.messages || []), newMsg];
    selectedContact.value = {
      ...selectedContact.value,
      messages: [...(selectedContact.value.messages || []), newMsg]
    };
    chatWindowRef.value?.loadMessages(dialogueId);
  }
};

// WebSocket辅助方法
const disconnectWebSocket = () => {
  clearReconnectTimer();
  if (ws.value) {
    // 主动关闭连接时设置code=1000表示正常关闭
    ws.value.close(1000, '用户主动退出');
    ws.value = null;
  }
  wsConnected.value = false; // 明确标记连接状态
};

const scheduleReconnect = () => {
  clearReconnectTimer();
  reconnectTimer = setTimeout(() => !wsConnected.value && initWebSocket(), 3000);
};

const clearReconnectTimer = () => {
  if (reconnectTimer) {
    clearTimeout(reconnectTimer);
    reconnectTimer = null;
  }
};

const processPendingMessages = () => {
  if (!chatSidebarRef.value || !pendingMessages.value.length) return;

  pendingMessages.value.forEach(msg => {
    chatSidebarRef.value.updateWithNewMessage(msg.dialogueId, msg.message);
  });

  pendingMessages.value = [];
};

// 导航处理
const handleNavClick = (type) => {
  if (type === 'chats') {
    currentView.value = 'chats';
    isGroupCreateMode.value = false;
  } else if (type === 'contacts') {
    currentView.value = 'contacts';
    isGroupCreateMode.value = false;
  }
};

// 会话选择
const onContactSelected = (contact) => {
  selectedContact.value = contact;
  currentView.value = 'chat';
  chatWindowRef.value?.loadMessages(contact.dialogueId);
};

// 好友选择
const onFriendSelected = (contact) => {
  if (isGroupCreateMode.value) {
    const index = selectedGroupMembers.value.findIndex(m => m.id === contact.id);
    index === -1
      ? selectedGroupMembers.value.push(contact)
      : selectedGroupMembers.value.splice(index, 1);
  } else {
    if (!addedContacts.value.some(c => c.id === contact.id)) {
      addedContacts.value.push(contact);
    }
    selectedContact.value = contact;
    currentView.value = 'chat';
    chatWindowRef.value?.loadMessages(contact.dialogueId);
  }
};

// 加载消息
const onLoadMessages = (dialogueId) => {
  chatWindowRef.value?.loadMessages(dialogueId);
};

// 同步消息到会话列表
const syncNewMessageToChatSidebar = async ({ contactId, message }) => {
  const avatarUrl = userInfo.value.avatarUrl;

  if (chatSidebarRef.value && ['chats', 'chat'].includes(currentView.value)) {
    chatSidebarRef.value.updateWithNewMessage(contactId, {
      ...message,
      sender: '我',
      isSelf: true,
      avatarUrl
    });
  }

  sendMessage(contactId, message.content);
};

// 发送消息
const sendMessage = (dialogueId, content) => {
  if (!wsConnected.value || !ws.value) {
    pendingMessages.value.push({
      dialogueId,
      message: {
        sender: '我',
        content,
        time: new Date().toISOString(),
        isSelf: true,
        avatarUrl: userInfo.value.avatarUrl
      }
    });
    return;
  }

  try {
    const targetId = selectedContact.value?.isGroup
      ? dialogueId // 群聊ID
      : selectedContact.value?.id; // 私聊用户ID
    ws.value.send(JSON.stringify({
      type: 'message',//看到了吗，这里处理的type是message
      dialogueId,
      content,
      fromId: userInfo.value.id,
      fromName: userInfo.value.userName,
      targetId, // 添加目标ID
      isGroup: selectedContact.value?.isGroup || false
    }));
  } catch (error) {
    console.error('消息发送失败:', error);
  }
};

// 发送好友请求
const sendFriendRequest = async (requestData) => {
  if (!wsConnected.value || !ws.value) {
    throw new Error('连接未建立，请稍后重试');
  }

  try {
    // 发送好友请求
    ws.value.send(JSON.stringify({
      type: 'friend_request',
      ...requestData
    }));
    return true; // 发送成功
  } catch (error) {
    console.error('发送好友请求失败:', error);
    throw error;
  }
};

// 群聊创建流程
const enterGroupCreateMode = () => {
  currentView.value = 'contacts';
  isGroupCreateMode.value = true;
  selectedGroupMembers.value = [];
};

const createGroupChat = async (selectedFriendIds) => {
  if (!Array.isArray(selectedFriendIds) || selectedFriendIds.length < 1) {
    alert('请至少选择1名好友');
    return;
  }

  const myUserId = localStorage.getItem('userId');
  if (!myUserId) {
    alert('未获取到用户ID');
    return;
  }

  try {
    const combinedIds = [Number(myUserId), ...selectedFriendIds];
    const res = await request.post('/user/createGroup', combinedIds);

    if (['SUCCESS', 'SUCCESs'].includes(res.data.code)) {
      const groupDialogueId = res.data.data;
      const groupContact = {
        id: groupDialogueId,
        name: `群聊(${combinedIds.length}人)`,
        avatar: '/images/group1.jpg',
        isGroup: true,
        dialogueId: groupDialogueId,
        users: [
          {
            id: userInfo.value.id,
            userName: userInfo.value.userName,
            avatarUrl: userInfo.value.avatarUrl
          },
          ...friendList.value.filter(friend => selectedFriendIds.includes(friend.id))
        ]
      };

      addedContacts.value.push(groupContact);
      selectedContact.value = groupContact;
      currentView.value = 'chat';
      isGroupCreateMode.value = false;
    }
  } catch (err) {
    console.error('创建群聊失败:', err);
    alert('创建群聊失败');
  }
};

// 添加好友流程（现在仅显示好友请求）
const enterAddFriendMode = () => {
  currentView.value = 'add-friend';
  // 进入页面时主动加载好友请求列表
  if (addFriendRef.value && userInfo.value.id) {
    addFriendRef.value.loadFriendRequests();
  }
};

// 刷新好友列表
const refreshFriendList = () => {
  friendListRef.value?.refreshFriendList();
  loadFriendListForGroup();
};

// 加载好友列表（用于群聊创建）
const loadFriendListForGroup = async () => {
  try {
    const res = await request.get('/user/getfriendlist', {
      params: { userId: userInfo.value.id }
    });
    if (['SUCCESS', 'SUCCESs'].includes(res.data.code)) {
      friendList.value = res.data.data || [];
    }
  } catch (err) {
    console.error('加载好友列表失败:', err);
  }
};

// 登录成功处理
const handleLoginSuccess = () => {
  isLoggedIn.value = true;
  initUserInfo();
  initWebSocket();
  loadFriendListForGroup();
  loadUnreadFriendRequests(); // 登录后加载未读请求
  currentView.value = 'chats';
};

// 新增退出登录处理方法
const logout = () => {
  // 1. 先断开WebSocket并清除重连定时器
  disconnectWebSocket();

  // 2. 清除本地存储
  localStorage.removeItem('token');
  localStorage.removeItem('userId');
  localStorage.removeItem('user_info');
  localStorage.removeItem('currentDialogueId');

  // 3. 更新状态
  isLoggedIn.value = false;
  userInfo.value = { userName: '', avatarUrl: '', id: '' };
  selectedContact.value = null;
  unreadFriendRequests.value = 0;

  // 4. 跳转到登录页
  router.push('/auth'); 
};
</script>

<style scoped>
.app-container {
  display: flex;
  height: 100vh;
  background: url('/images/bk.jpg') no-repeat center center fixed;
  background-size: cover;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}
</style>